require "net"
require "sim"
require "config"
require "log"
require "ril"
require "ntp"
module(..., package.seeall)

local msgQuene = {}

local function ismgJson(topic, payload, qos, user)
    local jsonstr = json.encode(payload)
    -- log.info("JSON", jsonstr)
    table.insert(msgQuene, { t = topic, p = jsonstr, q = qos, user = user })
end

function aLiInstertMsg(topic, payload)
    if aLiIotda.isReady() then
        ismgJson(topic, payload, 0, { cb = pubSysInfoOneCb })
    end
end

local function pubSysInfoOneCb(result)
end
--初始启动

function waitForSend()
    return #msgQuene > 0
end

function proc(mqttClient)
    while #msgQuene > 0 do
        local outMsg = table.remove(msgQuene, 1)
        local result = mqttClient:publish(outMsg.t, outMsg.p, outMsg.q)
        sys.publish("PUB")
        log.info("PUB Result", result)
        if outMsg.user and outMsg.user.cb then
            outMsg.user.cb(result, outMsg.user.para)
        end
        if not result then
            return false
        end
    end

    return true
end

function unInit()
    sys.publish("ALI_MQTT_CUSTOM_TASK_KILL")
    while #msgQuene > 0 do
        local outMsg = table.remove(msgQuene, 1)
        if outMsg.user and outMsg.user.cb then
            outMsg.user.cb(false, outMsg.user.para)
        end
    end
end

